package com.farm.system.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.farm.common.annotation.Log;
import com.farm.common.config.Config;
import com.farm.common.controller.BaseController;
import com.farm.common.domain.FileDO;
import com.farm.common.domain.Tree;
import com.farm.common.service.FileService;
import com.farm.common.utils.*;
import com.farm.shop.dao.FarmShopDao;
import com.farm.shop.domain.FarmShopDO;
import com.farm.system.domain.MenuDO;
import com.farm.system.service.MenuService;
import com.farm.system.shiro.UnicomUsernamePasswordToken;
import com.farm.utils.LineChars;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Controller
public class LoginController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private FarmShopDao farmShopDao;

    @Autowired
    MenuService menuService;
    @Autowired
    FileService fileService;
    @Autowired
    Config config;

    @GetMapping({"/", ""})
    String welcome(Model model) {

        return "redirect:/login";
    }

    @Log("请求访问主页")
    @GetMapping({"/index"})
    String index(Model model) {
        List<Tree<MenuDO>> menus = menuService.listMenuTree(getUserId());
        model.addAttribute("menus", menus);
        model.addAttribute("name", getUser().getName());
        FileDO fileDO = fileService.get(getUser().getPicId());
        if (fileDO != null && fileDO.getUrl() != null) {
            if (fileService.isExist(fileDO.getUrl())) {
                model.addAttribute("picUrl", fileDO.getUrl());
            } else {
                model.addAttribute("picUrl", "/img/photo_s.jpg");
            }
        } else {
            model.addAttribute("picUrl", "/img/photo_s.jpg");
        }
        model.addAttribute("username", getUser().getUsername());
        return "index_v1";
    }

    @GetMapping("/login")
    String login(Model model) {
        model.addAttribute("username", config.getUsername());
        model.addAttribute("password", config.getPassword());
        return "login";
    }

    @Log("登录")
    @PostMapping("/login")
    @ResponseBody
    R ajaxLogin(String username, String password, String verify, HttpServletRequest request) {
        try {
            // 从session中获取随机数
            String random = (String) request.getSession().getAttribute(RandomValidateCodeUtil.RANDOMCODEKEY);
            if (StringUtils.isBlank(verify)) {
                return R.error("请输入验证码");
            }
            if (random.equals(verify)) {
            } else {
                return R.error("请输入正确的验证码");
            }
        } catch (Exception e) {
            logger.error("验证码校验失败", e);
            return R.error("验证码校验失败");
        }
        try {
//            username = AesEncryptUtils.decrypt(username, "581e75b6a87a6789");
            username = username;
         //   password = AesEncryptUtils.decrypt(password, "581e75b6a87a6789");
            password = password;
        } catch (Exception e1) {
            e1.printStackTrace();
            return R.error("登录出错");
        }
       // password = MD5Utils.encrypt(username, password);
        password = password;
        UnicomUsernamePasswordToken token = new UnicomUsernamePasswordToken(username, password);
        token.setLoginType("sys");
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            return R.ok();
        } catch (AuthenticationException e) {
            return R.error("用户或密码错误");
        }
    }

    @GetMapping("/logout")
    String logout() {
        ShiroUtils.logout();
        return "redirect:/login";
    }

    /**
     *  首页统计图
     *
     * @return  main
     */
    @GetMapping("/main")
  //  @RequiresPermissions("farm:first:page")
    String main(Model model) {

        Long deptId = ShiroUtils.getUser().getDeptId();

        //  16是平台管理部
        if (deptId != 16){
            return "main2";
        }

//        饼状图  查询所有的农家数量
        int shopCount = farmShopDao.shopCount();
        model.addAttribute("shopCount", shopCount);

//        查询只包含住宿农家的数量
        int accomCount = farmShopDao.accomCount();
        model.addAttribute("accomCount", accomCount);

//        查询只包含住宿农家的数量
        int diningCount = farmShopDao.diningCount();
        model.addAttribute("diningCount", diningCount);

//        查询同时包含住宿和美食的农家数量
        int diningAndAccomCount = farmShopDao.diningAndAccomCount();
        model.addAttribute("diningAndAccomCount", diningAndAccomCount);

//        折线图  住宿总数据
        Map<Integer, Long> monthsMap = LineChars.getMonths();

        List<Integer> accomsMonth = new ArrayList<>(12);
        List<FarmShopDO> accoms = farmShopDao.getAccoms();
      accoms.forEach(v ->{
          String createTime = DateUtil.formatDateTime(v.getCreateTime());
          String month = StrUtil.sub(createTime, 5, 7);
          accomsMonth.add(Convert.toInt(month));
      });

      //  分组
        Map<Integer, Long> accomsMonthCount = accomsMonth.stream().collect(
                Collectors.groupingBy(Integer::intValue, Collectors.counting()));

        StringBuilder accomSb = new StringBuilder();
        monthsMap.putAll(accomsMonthCount);

        monthsMap.forEach((k , v ) -> accomSb.append(v + ","));

        log.info("折线图住宿数据:{}",accomSb.toString().substring(0,accomSb.toString().length()-1));
        model.addAttribute("accomsResult", accomSb.toString().substring(0,accomSb.toString().length()-1));

//        折线图  美食总数据
        List<Integer> diningMonth = new ArrayList<>(12);
        List<FarmShopDO> dinings = farmShopDao.getDining();
        dinings.forEach(v ->{
            String createTime = DateUtil.formatDateTime(v.getCreateTime());
            String month = StrUtil.sub(createTime, 5, 7);
            diningMonth.add(Convert.toInt(month));
        });

        //  分组
        Map<Integer, Long> diningsMonthCount = diningMonth.stream().collect(
                Collectors.groupingBy(Integer::intValue, Collectors.counting()));

        StringBuilder diningSb = new StringBuilder();
        monthsMap.putAll(diningsMonthCount);

        monthsMap.forEach((k , v ) -> diningSb.append(v + ","));

        log.info("折线图美食数据:{}",diningSb.toString().substring(0,diningSb.toString().length()-1));
        model.addAttribute("diningResult", diningSb.toString().substring(0,diningSb.toString().length()-1));

//        折线图  同时包含住宿和美食
        List<Integer> accomAndDiningMon = new ArrayList<>(12);
        List<FarmShopDO> accomAndDinings = farmShopDao.getAccomAndDinings();
        accomAndDinings.forEach(v ->{
            String createTime = DateUtil.formatDateTime(v.getCreateTime());
            String month = StrUtil.sub(createTime, 5, 7);
            accomAndDiningMon.add(Convert.toInt(month));
        });

        //  分组
        Map<Integer, Long> accomAndDiningMonCount = accomAndDiningMon.stream().collect(
                Collectors.groupingBy(Integer::intValue, Collectors.counting()));

        StringBuilder accomAndDiningSb = new StringBuilder();

        monthsMap.putAll(accomAndDiningMonCount);

        monthsMap.forEach((k , v ) -> accomAndDiningSb.append(v + ","));

        log.info("折线图住宿美食数据:{}",accomAndDiningSb.toString().substring(0,accomAndDiningSb.toString().length()-1));

       model.addAttribute("accomAndDiningResult", accomAndDiningSb.toString().substring(0,accomAndDiningSb.toString().length()-1));

        return "main";
    }

    /**
     * 生成验证码
     */
    @GetMapping(value = "/getVerify")
    public void getVerify(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setContentType("image/jpeg");// 设置相应类型,告诉浏览器输出的内容为图片
            response.setHeader("Pragma", "No-cache");// 设置响应头信息，告诉浏览器不要缓存此内容
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expire", 0);
            RandomValidateCodeUtil randomValidateCode = new RandomValidateCodeUtil();
            randomValidateCode.getRandcode(request, response);// 输出验证码图片方法
        } catch (Exception e) {
            logger.error("获取验证码失败>>>> ", e);
        }
    }

    @GetMapping(value = "/getVerifyCode")
    public void getVerifys(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setContentType("image/jpeg");// 设置相应类型,告诉浏览器输出的内容为图片
            response.setHeader("Pragma", "No-cache");// 设置响应头信息，告诉浏览器不要缓存此内容
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expire", 0);
            RandomValidateCodeUtil randomValidateCode = new RandomValidateCodeUtil();
            randomValidateCode.getRandcode(request, response);// 输出验证码图片方法
        } catch (Exception e) {
            logger.error("获取验证码失败>>>> ", e);
        }
    }
}
